package com.ysk.testapplication.qcm;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.util.SparseArray;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.rq.rvlibrary.BaseAdapter;
import com.rq.rvlibrary.BaseViewHolder;
import com.rq.rvlibrary.RecyclerUtil;
import com.ysk.testapplication.LOG;
import com.ysk.testapplication.qcm.img_load.ImageLoadUtil;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author RQ
 * date    2022-01-27 15:39
 */
public class ViewController {
  private static Handler mainHandler = new Handler(Looper.getMainLooper());
  private FillMoreMethod mMoreMethod;
  private OnViewCreate mOnViewCreate;
  private Object passObj;
  private Context mContext;

  public ViewController(Object obj) {
    if (obj == null) {
      LOG.e("ViewController", "ViewController:不能传入空内容");
      return;
    }
    if (obj instanceof Activity) {
      this.mContext = (Context) obj;
    } else if (obj instanceof Fragment) {
      this.mContext = ((Fragment) obj).getContext();
    } else if (obj instanceof BaseViewHolder) {
      this.mContext = ((BaseViewHolder) obj).itemView.getContext();
    } else {
      LOG.e("ViewController", "当前只支持：Activity、Fragment、BaseViewHolder");
      LOG.e("ViewController", "传入内容为:" + obj.getClass().getSimpleName());
    }
    this.passObj = obj;
    if (obj instanceof FillMoreMethod) {
      this.mMoreMethod = (FillMoreMethod) obj;
    }
  }

  private Context getContext() {
    return mContext;
  }

  public <T extends View> T getView(int id) {
    View finView = this.viewSparseArray.get(id);
    if (finView != null) {
      return (T) finView;
    }
    if (passObj != null) {
      View find = null;
      if (passObj instanceof Activity) {
        find = ((Activity) passObj).findViewById(id);
      } else if (passObj instanceof Fragment) {
        if (((Fragment) passObj).getView() != null) {
          find = ((Fragment) passObj).getView().findViewById(id);
        }
      } else if (passObj instanceof BaseViewHolder) {
        find = ((BaseViewHolder) passObj).itemView.findViewById(id);
      }
      if (find != null) {
        viewSparseArray.put(id, find);
        return (T) find;
      }
    }
    return null;
  }

  //页面子控件
  private SparseArray<View> viewSparseArray = new SparseArray<>();

  public void setData2View(final int viewId, final Object obj) {
    if (Looper.myLooper() == Looper.getMainLooper()) {//主线程
      setDataToView(viewId, obj);
    } else {
      mainHandler.post(() -> setDataToView(viewId, obj));
    }
  }

  private void setDataToView(int viewId, Object object) {
    if (viewSparseArray.get(viewId) != null) {
      setDataToView(viewSparseArray.get(viewId), object);
    } else {
      View v = getView(viewId);
      LOG.d("BaseController", viewId + ".setDataToView  " + viewSparseArray.indexOfValue(v));
      if (v != null) {
        if (viewSparseArray.indexOfValue(v) < 0) {
          viewSparseArray.append(viewId, v);
        }
        setDataToView(v, object);
      }
    }
  }

  protected final synchronized void setDataToView(View view, Object obj) {

    if (view == null) {
      LOG.utilLog("ViewEmpty");
      return;
    }
    if (mMoreMethod != null && mMoreMethod.fillCustomViewData(view, obj)) {
      return;
    }
    //    if (obj == null) {
    //      LOG.utilLog("DataEmpty hide");
    //      view.setVisibility(View.GONE);
    //      return;
    //    }
    if (obj instanceof Integer && ((int) obj == View.VISIBLE || (int) obj == View.GONE || (int) obj == View.INVISIBLE)) {
      view.setVisibility((int) obj);
      return;
    }
    if (obj instanceof ViewParam) {
      if (obj == ViewParam.ENABLE) {
        view.setEnabled(true);
      } else if (obj == ViewParam.UNABLE) {
        view.setEnabled(false);
      } else if (obj == ViewParam.CHECKABLE) {
        view.setClickable(true);
      } else if (obj == ViewParam.UNCHECKABLE) {
        view.setClickable(false);
      }
      return;
    }
    if (obj instanceof View.OnClickListener) {
      view.setOnClickListener((View.OnClickListener) obj);
      return;
    }
    //    if (obj instanceof OnRefuseAndLoadListener.Status && view instanceof SmartRefreshLayout) {
    //      if (obj == FinishRefuseAndLoad) {
    //        ((SmartRefreshLayout) view).finishLoadMore();
    //        ((SmartRefreshLayout) view).finishRefresh();
    //      } else if (obj == OnRefuseAndLoadListener.Status.FinishLoad) {
    //        ((SmartRefreshLayout) view).finishLoadMore();
    //      } else if (obj == OnRefuseAndLoadListener.Status.FinishRefuse) {
    //        ((SmartRefreshLayout) view).finishRefresh();
    //      } else if (obj == OnRefuseAndLoadListener.Status.loadAble_False) {
    //        ((SmartRefreshLayout) view).setEnableLoadMore(false);
    //      } else if (obj == OnRefuseAndLoadListener.Status.loadable_True) {
    //        ((SmartRefreshLayout) view).setEnableLoadMore(true);
    //      } else if (obj == OnRefuseAndLoadListener.Status.refreshable_False) {
    //        ((SmartRefreshLayout) view).setEnableRefresh(false);
    //      } else if (obj == OnRefuseAndLoadListener.Status.refreshable_True) {
    //        ((SmartRefreshLayout) view).setEnableRefresh(true);
    //      }
    //      return;
    //    }
    if (obj instanceof Boolean) {
      if (view instanceof CompoundButton) {
        ((CompoundButton) view).setChecked((boolean) obj);
      } else {
        view.setSelected((boolean) obj);
      }
      return;
    }
    if (view instanceof ImageView) {
      fillImageView((ImageView) view, obj);
    } else if (view instanceof TextView) {
      fillTextView((TextView) view, obj);
    } else if (view instanceof RecyclerView) {
      LOG.d("BaseController", "setDataToView.833:");
      if (obj instanceof RecyclerUtil) {
        fillRecyclerViewData((RecyclerView) view, (RecyclerUtil) obj);
      } else {
        fillRecyclerViewData((RecyclerView) view, obj);
      }
    } else if (view instanceof FrameLayout) {
      fillFrameLayout((FrameLayout) view, obj);
    }
  }

  protected void fillImageView(ImageView view, Object obj) {
    LOG.d("BaseController", (obj instanceof Drawable) + ".1126:" + obj.getClass());
    if (obj instanceof Bitmap) {
      view.setImageBitmap((Bitmap) obj);
    } else if (obj instanceof Integer) {
      view.setImageResource((int) obj);
    } else if (obj instanceof Drawable) {
      view.setImageDrawable((Drawable) obj);
    } else if (obj instanceof String) {
      String con = (String) obj;
      if (con.startsWith("#")) {
        view.setBackgroundColor(Color.parseColor(con));
      } else if (con.startsWith("http")) {
        ImageLoadUtil.display(getContext(), (String) obj, view);
      } else {
        LOG.d("BaseController", "fillImageView.未知图片:" + con);
      }
    }
  }

  protected void fillTextView(TextView view, Object obj) {
    if (obj == null) {
      view.setText("");
    } else if (obj instanceof CharSequence) {
      view.setText((CharSequence) obj);
    } else if (obj instanceof Integer) {
      view.setText((int) obj);
    } else {
      view.setText(String.valueOf(obj));
    }
  }

  protected void fillRecyclerViewData(RecyclerView recyclerView, Object obj) {
    if (obj instanceof BaseAdapter) {
      new RecyclerUtil((BaseAdapter) obj).set2View(recyclerView);
    } else if (obj instanceof RecyclerView.Adapter) {
      new RecyclerUtil((RecyclerView.Adapter) obj).set2View(recyclerView);
    } else if (obj instanceof RecyclerView.LayoutManager) {
      recyclerView.setLayoutManager((RecyclerView.LayoutManager) obj);
    } else if (obj instanceof RecyclerView.ItemDecoration) {
      recyclerView.addItemDecoration((RecyclerView.ItemDecoration) obj);
    }
  }

  protected void fillRecyclerViewData(RecyclerView recyclerView, RecyclerUtil util) {
    util.context(getContext());
    if (recyclerView.getLayoutManager() == null && util.context(getContext()).build() != null) {
      recyclerView.setLayoutManager(util.build());
    }
    if (util.adapter() != null) {
      recyclerView.setAdapter(util.adapter());
    }
    if (util.getData() != null) {
      RecyclerView.Adapter adapter = recyclerView.getAdapter();
      if (adapter instanceof BaseAdapter) {
        if (util.getPage() == 1) {
          ((BaseAdapter) adapter).setData(util.getData());
        } else {
          ((BaseAdapter) adapter).addData(util.getData());
        }
      } else if (adapter == null) {
        adapter = util.adapter();
        recyclerView.setAdapter(adapter);
      }
    }
    if (util.getDecoration() != null) {
      recyclerView.addItemDecoration(util.getDecoration());
    }
  }

  FragmentManager mFragmentManager;

  protected void fillFrameLayout(FrameLayout view, Object obj) {
    //    if (mFragmentManager == null) {
    //      mFragmentManager = activity.getSupportFragmentManager();
    //    }
    //    FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
    //    BaseFragment fragment = null;
    //    if (obj instanceof Class) {
    //      fragment = CommonFragment.instance((Class<BaseController>) obj);
    //    } else if (obj instanceof BaseFragment) {
    //      fragment = (BaseFragment) obj;
    //    }
    //    if (fragment == null) {
    //      LOG.d("BaseController", "fillFrameLayout.fragment == null");
    //      return;
    //    }
    //    FragmentTransaction ft = mFragmentTransaction;
    //    LOG.d("BaseController", "fillFrameLayout.fragment.getStrTag():" + fragment.getStrTag());
    //    Fragment showFg = null;
    //    String tagPage = null;
    //    Fragment show = null;
    //    for (Fragment item : mFragmentManager.getFragments()) {
    //      if (!item.isHidden()) {
    //        show = item;
    //      }
    //    }
    //    try {
    //      tagPage = (String) view.getTag(R.id.tag_key);
    //      showFg = mFragmentManager.findFragmentByTag(tagPage);
    //    } catch (Exception e) {
    //    }
    //    if (!fragment.isAdded() && null == mFragmentManager.findFragmentByTag(tagPage)) {
    //      if (showFg != null) {
    //        ft.hide(showFg).add(view.getId(), fragment, tagPage);
    //      } else {
    //        view.setTag(R.id.tag_key, tagPage);
    //        ft.add(view.getId(), fragment, tagPage);
    //      }
    //    } else { //已经加载进容器里去了....
    //      if (show != null) {
    //        ft.hide(show).show(fragment);
    //      } else {
    //        ft.show(fragment);
    //      }
    //    }
    //    if (!getActivity().isFinishing()) {
    //      ft.commitAllowingStateLoss();
    //      getActivity().getSupportFragmentManager().executePendingTransactions();
    //    }
  }

  public void onViewCreate() {
    if (mOnViewCreate != null) {
      mOnViewCreate.onViewCreate();
    }
  }
}
